package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.*;
import com.itheima.service.db.*;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
public class SoulQuestionManager {

    @DubboReference
    SoulQuestionService soulQuestionService;

    @DubboReference
    UserSoulTypeService userSoulTypeService;

    @DubboReference
    QuestionTextService questionTextService;

    @DubboReference
    QuestionOptionsService questionOptionsService;

    @DubboReference
    SoulReportService soulReportService;

    @DubboReference
    SoulDimensionService soulDimensionService;

    @DubboReference
    UserInfoService userInfoService;

    /**
     * 问卷列表
     *
     * @return
     */
    public ResponseEntity testSoul() {
        //1.获取登录用户的id
        Long userId = UserHolder.get().getId();
        //2.根据id获取用户类型信息
        UserSoulType userSoulType = userSoulTypeService.findByUserId(userId);
        List<SoulQuestion> soulQuestionList = soulQuestionService.findAll();
        //3.创建封装数据的集合
        List<SoulQuestionVo> voList = new ArrayList<>();


        if (CollUtil.isNotEmpty(soulQuestionList)) {
            for (SoulQuestion soulQuestion : soulQuestionList) {
                //4.根据类型id查询等级问题
                long typeId = soulQuestion.getId();
                List<QuestionText> questionTextList = questionTextService.findByTypeId(Integer.valueOf((int) typeId));
                //创建问题的vo
                List<QuestionTextVo> textVoList = new ArrayList<>();
                //4.根据问题id获取选项
                for (QuestionText questionText : questionTextList) {


                    List<QuestionOptions> optionsList = questionOptionsService.findByQuestionId(questionText.getId());
                    //创建选项的vo
                    List<QuestionOptionsVo> optionsVoList = new ArrayList<>();

                    for (QuestionOptions options : optionsList) {
                        QuestionOptionsVo optionsVo = new QuestionOptionsVo();
                        optionsVo.setId(options.getId().toString());
                        optionsVo.setOption(options.getOpt());
                        //封装数据
                        optionsVoList.add(optionsVo);
                    }
                    QuestionTextVo textVo = new QuestionTextVo();
                    textVo.setId(questionText.getId().toString());
                    textVo.setQuestion(questionText.getQuestion());
                    textVo.setOptions(optionsVoList);
                    textVoList.add(textVo);
                }

                //6.判断用户的等级信息是不是null
                if (userSoulType == null) {
                    //如果是新入用户
                    if (soulQuestion.getLevel().equals("初级")) {
                        soulQuestion.setIsLock(0);
                    }
                } else {
                    //如果有等级信息
                    String userLevel = userSoulType.getUserLevel();
                    switch (userLevel) {
                        case "初级": {
                            if (soulQuestion.getLevel().equals("初级") || soulQuestion.getLevel().equals("中级")) {
                                soulQuestion.setIsLock(0);
                            }
                            break;
                        }
                        case "中级": {
                            soulQuestion.setIsLock(0);
                            break;
                        }
                        case "高级": {
                            soulQuestion.setIsLock(0);
                            break;
                        }
                    }
                }
                SoulQuestionVo vo = new SoulQuestionVo();
                BeanUtil.copyProperties(soulQuestion, vo);
                vo.setQuestions(textVoList);
                //7.根据用户id查询报告id
                if (userSoulType != null) {
                    Integer reportId = userSoulType.getReportId();
                    vo.setReportId(reportId.toString());
                } else {
                    vo.setReportId(null);
                }
                //8.将数据添加到集合中
                voList.add(vo);
            }
        }
        return ResponseEntity.ok(voList);
    }


    /**
     * 提交问卷答案,生成报告
     * @param answersList
     * @return
     */
    public ResponseEntity commitQuestion(List<Answers> answersList) {
        //1.获取用户id
        Long userId = UserHolder.get().getId();
        //2.根据用户回答的问题的答案计算总分
        int sumScore = 0;
        if (CollUtil.isNotEmpty(answersList)) {
            for (Answers answers : answersList) {
                //获取选项id,查询对应选项的分数
                String optionId = answers.getOptionId();
                QuestionOptions option = questionOptionsService.findById(optionId);
                Integer score = option.getScore();
                //计算出总分
                sumScore += score;
            }
        }
        //3.根据总分生成类型
        SoulReport soulReport = soulReportService.findByScore(sumScore);
        Integer reportId = soulReport.getId();

        //5.根据用户id查询用户原始信息
        UserSoulType userSoulType = userSoulTypeService.findByUserId(userId);
        if (userSoulType == null) {
            //新增用户信息
            userSoulType = new UserSoulType();
            userSoulType.setUserId(userId);
            userSoulType.setUserScore(sumScore);
            userSoulType.setReportId(reportId);
            userSoulType.setUserLevel("初级");
            userSoulTypeService.save(userSoulType);
        } else {
            //更新用户信息
            //1.判断用户等级是什么
            if ("高级".equals(userSoulType.getUserLevel())) {
                //如果用户已经是高级权限,就不需要修改
                userSoulType.setUserScore(sumScore);
                userSoulType.setReportId(reportId);
            } else {
                //判断题目的等级是不是中级或者高级
                Answers answers = answersList.get(0);
                QuestionText questionText = questionTextService.findById(answers.getQuestionId());
                //去获取试题等级类型id
                SoulQuestion soulQuestion = soulQuestionService.findById(questionText.getTypeId());
                String level = soulQuestion.getLevel();
                if (level.equals("中级") || level.equals("高级")) {
                    userSoulType.setUserLevel(level);
                    userSoulType.setUserScore(sumScore);
                    userSoulType.setReportId(reportId);
                } else {
                    userSoulType.setUserScore(sumScore);
                    userSoulType.setReportId(reportId);
                }
            }
            //更新用户信息
            userSoulTypeService.update(userSoulType);
        }
        return ResponseEntity.ok(reportId.toString());
    }


    /**
     * 查询报告详情
     * @param reportId
     * @return
     */
    public ResponseEntity findReportById(Integer reportId) {
        //1.获取当前用户id
        Long userId = UserHolder.get().getId();
        //2.根据报告id查询报告内容
        SoulReport report = soulReportService.findById(reportId);
        //3.根据报告类型查询维度
        List<SoulDimension> dimensionList = soulDimensionService.findByReportId(reportId);
        List<SoulDimensionVo> dimensionVoList = new ArrayList<>();
        if (CollUtil.isNotEmpty(dimensionList)) {
            for (SoulDimension soulDimension : dimensionList) {
                SoulDimensionVo dimensionVo = new SoulDimensionVo();
                dimensionVo.setKey(soulDimension.getDimensionKey());
                dimensionVo.setValue(soulDimension.getDimensionValue());
                dimensionVoList.add(dimensionVo);
            }
        }
        //4.查询根据报告id查询同报告类型用户id
        List<UserSoulType> userSoulTypeList = userSoulTypeService.findByReportId(reportId);
        List<UserInfoDto> userInfoDtos = new ArrayList<>();
        //5.根据用户id查询用户信息
        if (CollUtil.isNotEmpty(userSoulTypeList)) {
            for (UserSoulType userSoulType : userSoulTypeList) {
                Long id = userSoulType.getUserId();
                //排除自己
                if (userId != id) {
                    UserInfo userInfo = userInfoService.findById(id);
                    //将用户信息封装
                    UserInfoDto infoDto = new UserInfoDto();
                    infoDto.setId(Math.toIntExact(userInfo.getId()));
                    infoDto.setAvatar(userInfo.getAvatar());
                    userInfoDtos.add(infoDto);
                }
            }
        }
        //封装所有数据
        SoulReportVo reportVo = new SoulReportVo();
        reportVo.setConclusion(report.getConclusion());
        reportVo.setCover(report.getCover());
        reportVo.setDimensions(dimensionVoList);
        reportVo.setSimilarYou(userInfoDtos);

        return ResponseEntity.ok(reportVo);
    }
}
